package com.itita.ww2.game.pay;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.channel.payment.OrderInfo;

public class PaymentManager {
	private static final Logger logger = LoggerFactory.getLogger(PaymentManager.class);
	// LasyLoad
	private static PaymentManager instance = new PaymentManager();

	public static PaymentManager getInstance() {
		return instance;
	}

	private Cache<Integer, OrderInfo> orders; // 订单缓存项(每次支付一次)

	private PaymentManager() {
		init();
	}

	private void init() {
		// @formatter:off
		orders = CacheBuilder.newBuilder()
				.maximumSize(25000)
				.expireAfterAccess(5, TimeUnit.MINUTES)
				.expireAfterWrite(5, TimeUnit.MINUTES)
				.recordStats()
				.initialCapacity(100)
				.removalListener(new RemovalListener<Integer, OrderInfo>() {

					@Override
					public void onRemoval(RemovalNotification<Integer, OrderInfo> arg0) {
						logger.info("OrderInfo has removed. uid:{}, orderId:{}", arg0.getKey(),
								arg0.getValue().getOrderId());
					}
				})
				.build();
		// @formatter:on
	}

	/**
	 * 获取缓存的订单
	 */
	public OrderInfo getOrderInfoByUid(UserProfile userProfile) {
		OrderInfo ret = null;
		try {
			ret = orders.get(userProfile.getUid(), new Callable<OrderInfo>() {
				@Override
				public OrderInfo call() throws Exception {
					return null;
				}
			});
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public void removeOrderInfo(UserProfile userProfile) {
		orders.invalidate(userProfile.getUid());
	}

	public boolean isOrderInfoExists(UserProfile userProfile, String orderId) {
		OrderInfo ret = getOrderInfoByUid(userProfile);
		if (ret == null) {
			return false;
		}
		return ret.getOrderId().equalsIgnoreCase(orderId);
	}

	/**
	 * 生成新订单
	 */
	public OrderInfo createNewOrder(UserProfile userProfile) {
		if (this.orders.asMap().containsKey(userProfile.getUid())) {
			logger.warn("OrderInfo: uid:{}, orderId:{} has exists. force override!", userProfile.getUid(),
					getOrderInfoByUid(userProfile).getOrderId());
			// return false;
		}
		OrderInfo ret = OrderInfo.newOrder();
		if (ret == null) {
			return null;
		}
		this.orders.put(userProfile.getUid(), ret);
		logger.debug("new order: {}", ret.getOrderId());
		return ret;
	}
}
